using UnityEngine;
using System.Collections;

public class TreasureSpawner : MonoBehaviour
{
    [Header("垂直列设置")]
    public GameObject treasureChestPrefab;
    public int chestCount = 7; // 宝箱数量（7行）
    public float chestSpacing = 1.2f; // 宝箱间距
    public Vector2 startPosition = new Vector2(-1.43f, 5.56f); // 起始位置（顶部）
    public bool autoRefill = true; // 自动补充宝箱

    [Header("宝箱配置")]
    public int chestHealth = 3; // 统一血量
    public PowerUpController.PowerUpType[] powerUpSequence = {
        PowerUpController.PowerUpType.SpreadShot,
        PowerUpController.PowerUpType.BurstFire,
        PowerUpController.PowerUpType.UpgradedBullet,
        PowerUpController.PowerUpType.BulletUpgradePowerUp,
        PowerUpController.PowerUpType.Clone
    }; // 道具序列，循环使用

    [Header("调试设置")]
    public bool showDebugInfo = true;
    public bool showGizmos = true;

    // 单行管理
    private TreasureChestController[] chestArray;
    private bool isInitialized = false;

    void Start()
    {
        InitializeChests();
    }

    void Update()
    {
        if (!isInitialized) return;

        if (showDebugInfo)
        {
            int activeChests = CountActiveChests();
            Debug.Log($"活跃宝箱数量: {activeChests}/{chestCount}");
        }
    }

    void InitializeChests()
    {
        // 创建默认宝箱预制体（如果没有设置）
        if (treasureChestPrefab == null)
        {
            CreateDefaultTreasureChest();
        }

        // 初始化单行数组
        chestArray = new TreasureChestController[chestCount];

        // 生成所有宝箱
        SpawnAllChests();

        isInitialized = true;

        Debug.Log($"宝箱垂直列已初始化: {chestCount}个宝箱");
    }

    void SpawnAllChests()
    {
        for (int i = 0; i < chestCount; i++)
        {
            SpawnChestAtIndex(i);
        }
    }

    void SpawnChestAtIndex(int index)
    {
        if (index < 0 || index >= chestCount) return;
        if (chestArray[index] != null) return; // 位置已被占用

        Vector3 spawnPosition = GetChestPosition(index);

        GameObject treasure = Instantiate(treasureChestPrefab, spawnPosition, Quaternion.identity);

        // 配置宝箱属性
        TreasureChestController treasureController = treasure.GetComponent<TreasureChestController>();
        if (treasureController != null)
        {
            // 根据索引循环分配道具类型
            PowerUpController.PowerUpType powerUpType = powerUpSequence[index % powerUpSequence.Length];

            treasureController.SetChestProperties(chestHealth, powerUpType, 0f); // 不移动

            // 存储索引信息
            treasureController.gridRow = index; // 垂直排列，行为索引
            treasureController.gridCol = 0; // 单列，列固定为0

            if (showDebugInfo)
            {
                Debug.Log($"生成宝箱: 索引={index}, 世界位置={spawnPosition}, 道具类型={powerUpType}, gridRow={index}");
            }
        }

        // 将宝箱添加到数组中
        chestArray[index] = treasureController;

        // 监听宝箱销毁事件
        StartCoroutine(MonitorChest(index, treasure));


    }

    Vector3 GetChestPosition(int index)
    {
        float x = startPosition.x;
        float y = startPosition.y - index * chestSpacing; // 垂直向下排列
        return new Vector3(x, y, 0f);
    }

    int CountActiveChests()
    {
        int count = 0;
        for (int i = 0; i < chestCount; i++)
        {
            if (chestArray[i] != null)
            {
                count++;
            }
        }
        return count;
    }

    System.Collections.IEnumerator MonitorChest(int index, GameObject treasure)
    {
        if (showDebugInfo)
        {
            Debug.Log($"开始监听宝箱: 索引={index}, 位置={treasure.transform.position}");
        }

        while (treasure != null)
        {
            yield return new WaitForSeconds(0.1f);
        }

        // 宝箱被销毁，清空数组位置
        if (index >= 0 && index < chestCount)
        {
            chestArray[index] = null;
        }

        if (showDebugInfo)
        {
            Debug.Log($"宝箱已销毁，清空索引: {index}，位置应该是: {GetChestPosition(index)}");
        }

        // 如果启用自动补充，则重新生成
        if (autoRefill)
        {
            yield return new WaitForSeconds(2f); // 等待2秒后重新生成
            SpawnChestAtIndex(index);
        }
    }

    void CreateDefaultTreasureChest()
    {
        // 创建默认宝箱预制体
        GameObject chest = new GameObject("DefaultTreasureChest");

        // 添加精灵渲染器
        SpriteRenderer spriteRenderer = chest.AddComponent<SpriteRenderer>();
        spriteRenderer.sprite = CreateChestSprite();
        spriteRenderer.color = Color.yellow;

        // 添加刚体
        Rigidbody2D rb = chest.AddComponent<Rigidbody2D>();
        rb.gravityScale = 0f;
        rb.freezeRotation = true;

        // 添加碰撞器
        BoxCollider2D collider = chest.AddComponent<BoxCollider2D>();
        collider.size = new Vector2(0.8f, 0.8f);
        collider.isTrigger = true;

        // 添加宝箱控制器
        chest.AddComponent<TreasureChestController>();

        // 设置标签
        chest.tag = "TreasureChest";

        treasureChestPrefab = chest;

        Debug.Log("已创建默认宝箱预制体");
    }

    Sprite CreateChestSprite()
    {
        // 创建简单的宝箱精灵
        Texture2D texture = new Texture2D(32, 32);
        Color[] pixels = new Color[32 * 32];

        for (int i = 0; i < pixels.Length; i++)
        {
            int x = i % 32;
            int y = i / 32;

            // 创建宝箱形状
            if ((x >= 4 && x <= 28 && y >= 8 && y <= 24) || // 主体
                (x >= 8 && x <= 24 && y >= 20 && y <= 28))   // 盖子
            {
                pixels[i] = Color.yellow;
            }
            else if ((x >= 14 && x <= 18 && y >= 12 && y <= 20)) // 锁
            {
                pixels[i] = Color.black;
            }
            else
            {
                pixels[i] = Color.clear;
            }
        }

        texture.SetPixels(pixels);
        texture.Apply();

        return Sprite.Create(texture, new Rect(0, 0, 32, 32), new Vector2(0.5f, 0.5f));
    }

    // 公共方法：在指定位置生成宝箱
    public void SpawnTreasureAtPosition(Vector3 position)
    {
        GameObject treasure = Instantiate(treasureChestPrefab, position, Quaternion.identity);

        // 配置宝箱属性
        TreasureChestController treasureController = treasure.GetComponent<TreasureChestController>();
        if (treasureController != null)
        {
            // 随机选择道具类型
            PowerUpController.PowerUpType randomPowerUp = powerUpSequence[Random.Range(0, powerUpSequence.Length)];

            // 设置宝箱属性
            treasureController.SetChestProperties(chestHealth, randomPowerUp, 2f);
        }

        Debug.Log($"在位置 {position} 生成宝箱");
    }

    void OnDrawGizmos()
    {
        if (!showGizmos) return;

        Gizmos.color = Color.yellow;

        // 绘制宝箱位置
        for (int i = 0; i < chestCount; i++)
        {
            Vector3 position = GetChestPosition(i);
            Gizmos.DrawWireCube(position, Vector3.one * 0.8f);

            // 如果有宝箱，用绿色标记
            if (Application.isPlaying && chestArray != null && i < chestArray.Length && chestArray[i] != null)
            {
                Gizmos.color = Color.green;
                Gizmos.DrawCube(position, Vector3.one * 0.6f);
                Gizmos.color = Color.yellow;
            }
        }
    }
}
